<template>
  <div class="ai-generation">
    <!-- 问候语区 -->
    <div class="greeting-section">
      <h1>{{ greeting }}，有什么我能帮你的吗？</h1>
    </div>

    <!-- 题目生成参数配置区 -->
    <div class="config-section">
      <h2>题目生成参数配置</h2>
      <div class="config-controls">
        <!-- 新增学科选择项 -->
        <div class="config-item">
          <label>学科</label>
          <select v-model="subject">
            <!-- <option>全部学科</option> -->
            <option v-for="course in courses" :key="course.id" :value="course.courseName">{{ course.courseName }}</option>
          </select>
        </div>
        <div class="config-item">
          <label>题目难度</label>
          <select v-model="difficulty">
            <option v-for="level in difficultyLevels" :key="level" :value="level">{{ level }}</option>
          </select>
        </div>
        <div class="config-item">
          <label>题目类型</label>
          <select v-model="type">
            <option v-for="questionType in questionTypes" :key="questionType" :value="questionType">{{ questionType }}</option>
          </select>
        </div>
        <div class="config-item">
          <label>关联知识点</label>
          <select v-model="knowledge">
            <!-- <option value="">全部知识点</option> -->
            <option v-for="title in knowledgeTitles" :key="title" :value="title">{{ title }}</option>
          </select>
        </div>
      </div>
    </div>

    <!-- 交互输入区 -->
    <div class="input-section">
      <button class="deep-think-btn">深度思考</button>
      <div class="input-box">
        <input type="text" v-model="inputText" placeholder="发消息、输入想问的问题/ 选择文件" @keyup.enter="handleSend">
        <div class="input-icons">
          <i class="material-icons">content_cut</i>
          <i class="material-icons">mic</i>
          <button 
            class="send-btn" 
            @click="handleSend" 
            :disabled="isGenerating"
          >
            <i 
              class="material-icons"
              :class="{ 'spin': isGenerating }"
            >
              {{ isGenerating ? 'autorenew' : 'send' }}
            </i>
          </button>
        </div>
      </div>
    </div>
    <!-- 生成结果预览区 -->
    <div class="preview-section">
      <div class="preview-header">
        <h2>生成结果预览</h2>
        <div class="preview-controls">
          <select>
            <option>全部结果</option>
          </select>
          <button class="regenerate-btn" @click="handleSend">重新生成</button>
        </div>
      </div>
      <!-- 动态显示 AI 生成的题目，添加过渡动画 -->
      <transition-group name="fade" tag="div">
        <div v-for="(question, index) in generatedQuestions" :key="question.id || index" class="question-card">
          <!-- 调试信息 -->
          <div v-if="!question.content" class="debug-info">题目内容为空: {{ JSON.stringify(question) }}</div>
          <div v-if="question.content" class="question-content" v-html="formatRichText(question)"> 
          </div> 
          <!-- 调试信息 -->
          <!-- <div v-if="!question.knowledge && !question.difficulty && !question.type" class="debug-info">元数据为空: {{ JSON.stringify(question) }}</div> -->
          <div v-if="question.knowledge || question.difficulty || question.type" class="question-meta"> 
            <span v-if="question.knowledge">适用知识点：{{ question.knowledge }}</span> 
            <span v-if="question.difficulty">当前难度：{{ question.difficulty }}</span> 
            <span v-if="question.type"> | 题目类型：{{ question.type.replace('\n', '') }}</span> 
          </div> 
          <div class="question-actions">
            <i class="material-icons" @click="openConfirmDialog(index)">check</i>
            <i class="material-icons" @click="openEditDialog(index)">edit</i>
            <!-- <i class="material-icons">delete</i> -->
          </div>
        </div>
      </transition-group>
    </div>
<!-- Edit Dialog -->
<div class="edit-dialog" v-if="showEditDialog">
      <div class="dialog-overlay" @click="cancelEdit"></div>
      <div class="dialog-content">
        <h3>编辑题目</h3>
        <div class="form-group">
          <label>题目内容</label>
          <textarea v-model="currentQuestion.content"></textarea>
        </div>
        <!-- 新增解析内容显示 -->
        <div class="form-group">
          <label>解析内容</label>
          <textarea v-model="currentQuestion.analysis" readonly></textarea>
        </div>
        <div class="form-group">
          <label>适用知识点</label>
          <select v-model="currentQuestion.knowledge">
            <option v-for="title in knowledgeTitles" :key="title" :value="title">{{ title }}</option>
          </select>
        </div>
        <div class="form-group">
          <label>题目难度</label>
          <select v-model="currentQuestion.difficulty">
            <option v-for="level in difficultyLevels" :key="level" :value="level">{{ level }}</option>
          </select>
        </div>
        <div class="form-group">
          <label>题目类型</label>
          <select v-model="currentQuestion.type">
            <option v-for="questionType in questionTypes" :key="questionType" :value="questionType">{{ questionType }}</option>
          </select>
        </div>
        <div class="dialog-actions">
          <button class="cancel-btn" @click="cancelEdit">取消</button>
          <button class="confirm-btn" @click="confirmEdit">确认修改</button>
        </div>
      </div>
    </div>

    <!-- 确认对话框 -->
    <div class="confirm-dialog" v-if="showConfirmDialog">
      <div class="dialog-overlay" @click="cancelConfirm"></div>
      <div class="dialog-content">
        <h3>确认题目</h3>
        <div class="form-group">
          <label>题目内容</label>
          <div class="preview-text">{{ currentQuestion.content }}</div>
        </div>
        <!-- 新增解析内容显示 -->
        <div class="form-group">
          <label>解析内容</label>
          <div class="preview-text">{{ currentQuestion.analysis }}</div>
        </div>
        <div class="form-group">
          <label>适用知识点</label>
          <select v-model="currentQuestion.knowledge">
            <option v-for="title in knowledgeTitles" :key="title" :value="title">{{ title }}</option>
          </select>
        </div>
        <div class="form-group">
          <label>题目难度</label>
          <select v-model="currentQuestion.difficulty">
            <option v-for="level in difficultyLevels" :key="level" :value="level">{{ level }}</option>
          </select>
        </div>
        <div class="form-group">
          <label>题目类型</label>
          <select v-model="currentQuestion.type">
            <option v-for="questionType in questionTypes" :key="questionType" :value="questionType">{{ questionType }}</option>
          </select>
        </div>
        <div class="dialog-actions">
          <button class="cancel-btn" @click="cancelConfirm">取消</button>
          <button class="confirm-btn" @click="submitQuestion">确认并上传</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import axios from 'axios';
import { generateQuestionApi } from '@/api/ai';
import { nextTick } from 'vue';
import katex from 'katex';
import { computed } from 'vue';

// 新增时间问候语计算
const greeting = computed(() => {
  const hour = new Date().getHours();
  if (hour >= 5 && hour < 11) return '早上好';
  if (hour >= 11 && hour < 14) return '中午好';
  if (hour >= 14 && hour < 18) return '下午好';
  return '晚上好';
});

const subject = ref(''); // 初始化为空
const courses = ref([]);
const difficultyLevels = ref([]);
const questionTypes = ref([]);

onMounted(async () => {
  try {
    // console.log('开始请求课程数据');
    const token = localStorage.getItem('token');
    const coursesResponse = await axios.get('http://localhost:8080/ai/courses', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    // console.log('课程数据请求成功，响应数据:', coursesResponse.data);
    if (Array.isArray(coursesResponse.data)) {
      courses.value = coursesResponse.data;
      // console.log('课程数据已成功赋值给 courses:', courses.value);
      // 设置默认选择第一个课程
      if (courses.value.length > 0) {
        subject.value = courses.value[0].courseName;
      }
    } else {
      console.error('后端返回的课程数据不是数组:', coursesResponse.data);
    }

    // console.log('开始请求题目难度数据');
    const difficultyResponse = await axios.get('http://localhost:8080/ai/difficultyLevels', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    // console.log('题目难度数据请求成功，响应数据:', difficultyResponse.data);
    if (Array.isArray(difficultyResponse.data)) {
      difficultyLevels.value = difficultyResponse.data;
      // console.log('题目难度数据已成功赋值给 difficultyLevels:', difficultyLevels.value);
    } else {
      // console.error('后端返回的题目难度数据不是数组:', difficultyResponse.data);
    }

    // console.log('开始获取题目类型数据');
    const response = await axios.get('http://localhost:8080/ai/questionTypes', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    // console.log('题目类型数据获取成功:', response.data);
    questionTypes.value = response.data;
  } catch (error) {
    // console.error('获取题目类型失败:', error);
  }
});

const difficulty = ref('简单')
const type = ref('选择题')
const knowledge = ref('');
const knowledgeTitles = ref([]);

// 监听 subject 的变化，用户选择学科时调用接口
watch(subject, async (newSubject) => {
  try {
    // 找到对应 courseName 的 courseId
    const selectedCourse = courses.value.find(course => course.courseName === newSubject);
    if (selectedCourse) {
      const courseId = selectedCourse.id;
      // console.log('开始获取关联知识点数据，使用 courseId:', courseId);
      const token = localStorage.getItem('token');
      const response = await axios.get('http://localhost:8080/ai/knowledgeTitles', {
        headers: {
          Authorization: `Bearer ${token}`
        },
        params: {
          courseId: courseId
        }
      });
      // console.log('关联知识点数据获取成功:', response.data);
      knowledgeTitles.value = response.data;

      // 每次学科变化后，设置关联知识点默认选择第一个选项
      if (knowledgeTitles.value.length > 0) {
        knowledge.value = knowledgeTitles.value[0];
      }
    } else {
      console.error('未找到对应的课程信息');
    }
  } catch (error) {
    console.error('获取关联知识点失败:', error);
  }
});
const showEditDialog = ref(false)
const showConfirmDialog = ref(false) 
const currentQuestion = ref({
  content: '计算光速飞船以 0.8c 飞行时的时间膨胀因子（要求写出推导过程）',
  knowledge: '狭义相对论 - 时间膨胀效应',
  difficulty: '中等',
  type: '计算题'
})

const inputText = ref('');
const generatedQuestions = ref([]);

const openEditDialog = (index) => {
  if (generatedQuestions.value[index]) {
    currentQuestion.value = { ...generatedQuestions.value[index] };
    showEditDialog.value = true;
  }
};

const openConfirmDialog = (index) => {
  if (generatedQuestions.value[index]) {
    currentQuestion.value = { ...generatedQuestions.value[index] };
    showConfirmDialog.value = true;
  }
};

function cancelEdit() {
  showEditDialog.value = false
}

const submitQuestion = async () => {
  try {
    const token = localStorage.getItem('token');
    // 找到当前选择学科对应的课程 ID
    const selectedCourse = courses.value.find(course => course.courseName === subject.value);
    if (!selectedCourse) {
      console.error('未找到对应的课程信息');
      return;
    }
    const courseId = selectedCourse.id;

    // 合并课程 ID 到要提交的数据中
    const dataToSubmit = {
      ...currentQuestion.value,
      courseId: courseId
    };

    const response = await axios.post('http://localhost:8080/ai/saveQuestion', dataToSubmit, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    console.log('题目保存成功', response.data);
    showConfirmDialog.value = false;
  } catch (error) {
    console.error('题目保存失败', error);
    // 可以在这里添加错误处理逻辑，例如显示错误提示
  }
};

function cancelConfirm() {
  showConfirmDialog.value = false
}

// 添加响应式变量
const isGenerating = ref(false);

const handleSend = async () => {
  if (isGenerating.value) return; // 如果正在生成，直接返回
  try {
    isGenerating.value = true; // 开始生成，设置为 true
    const params = {
      subject: subject.value,
      difficulty: difficulty.value,
      type: type.value,
      knowledge: knowledge.value,
      question: inputText.value
    };

    console.log('即将发送的请求参数:', params);

    const response = await generateQuestionApi(params);
    console.log('API 响应数据:', response.data);

    // 解析后端返回的 Markdown 内容
    const questions = response.data.split('### ').filter(Boolean).map(questionStr => {
      // 确保正则表达式正确匹配
      const contentMatch = questionStr.match(/\*\*题目：\*\*(.*?)\*\*解析：\*\*/s);
      const content = contentMatch ? contentMatch[1].trim().replace(/\*\*/g, '').replace(/\n/g, ' ') : '';

      const knowledgeMatch = questionStr.match(/\*\*知识点：\*\*(.*?)\n/);
      const knowledge = knowledgeMatch ? knowledgeMatch[1].trim().replace(/\*\*/g, '').replace(/\n/g, ' ') : '';

      const typeMatch = questionStr.match(/\*\*题目类型：\*\*(.*?)\n/);
      const type = typeMatch ? typeMatch[1].trim().replace(/\*\*/g, '').replace(/\n/g, ' ') : '';

      const difficultyMatch = questionStr.match(/\*\*题目难度：\*\*(.*?)\n/);
      const difficulty = difficultyMatch ? difficultyMatch[1].trim().replace(/\*\*/g, '').replace(/\n/g, ' ') : '';

      const analysisMatch = questionStr.match(/\*\*解析：\*\*(.*)/s);
      const analysis = analysisMatch ? analysisMatch[1].trim().replace(/\*\*/g, '').replace(/\n/g, ' ') : '';

      return {
        type,
        difficulty,
        content,
        knowledge,
        rawContent: '### ' + questionStr,
        analysis // 新增解析内容属性
      };
    }).filter(question => question.content);

    generatedQuestions.value = [...generatedQuestions.value, ...questions];
    console.log('生成的题目数据:', generatedQuestions.value);

    // 确保DOM更新后再滚动到最新内容
    await nextTick();
    const previewSection = document.querySelector('.preview-section');
    if (previewSection) {
      previewSection.scrollTop = previewSection.scrollHeight;
    }
    // console.log('DOM 已更新');
  } catch (error) {
    console.error('API 请求出错:', error);
  } finally {
    isGenerating.value = false; // 生成结束，设置为 false
  }
};

const confirmEdit = () => {
  const index = generatedQuestions.value.findIndex(q => q.content === currentQuestion.value.content);
  if (index !== -1) {
    generatedQuestions.value[index] = { ...currentQuestion.value };
  }
  showEditDialog.value = false;
};

const formatRichText = (question) => {
  try {
    if (!question.rawContent) {
      console.error('题目原始内容为空:', question);
      return '';
    }
    let content = question.rawContent;
    // console.log('原始内容:', content);
    // 处理标题
    content = content.replace(/#{3}\s*(.*)/g, '<h3>$1</h3>');
    // 处理加粗文本
    content = content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
    // 处理数学公式，识别 $...$、$$...$$ 和 \(...\)、\[...\] 格式
    content = content.replace(/\$\$(.*?)\$\$/gs, (match, formula) => {
      // 确保 \times 被正确渲染，添加 trust: true
      return katex.renderToString(formula, { throwOnError: false, displayMode: true, trust: true });
    });
    content = content.replace(/\$(.*?)\$/g, (match, formula) => {
      // 确保 \times 被正确渲染，添加 trust: true
      return katex.renderToString(formula, { throwOnError: false, displayMode: false, trust: true });
    });
    content = content.replace(/\\\((.*?)\\\)/g, (match, formula) => {
      // 确保 \times 被正确渲染，添加 trust: true
      return katex.renderToString(formula, { throwOnError: false, displayMode: false, trust: true });
    });
    content = content.replace(/\\\[(.*?)\\\]/gs, (match, formula) => {
      // 确保 \times 被正确渲染，添加 trust: true
      return katex.renderToString(formula, { throwOnError: false, displayMode: true, trust: true });
    });
    // 处理列表项
    content = content.replace(/^- (.*)/gm, '<div>- $1</div>');
    content = content.replace(/^(\d+)\. (.*)/gm, '<div>$1. $2</div>');
    // 处理代码块
    content = content.replace(/```(\w+)?\s*([\s\S]*?)```/g, (match, lang, code) => {
      return `<pre><code${lang ? ` class="${lang}"` : ''}>${code.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code></pre>`;
    });
    // 处理换行符
    content = content.replace(/\n/g, '<br>');

    // console.log('处理后的内容:', content);
    return content;
  } catch (error) {
    console.error('格式化富文本时出错:', error);
    return question.rawContent || '';
  }
};
</script>

<style scoped>
.ai-generation {
  padding: 2rem;
  /* background-color: #1a1a1a; */
  min-height: calc(100vh - 70px);
  /* color: white; */
}

.greeting-section {
  text-align: center;
  margin-bottom: 2rem;
}

.greeting-section h1 {
  font-family: 'Noto Sans SC', sans-serif;
  font-weight: 500;
  font-size: 28px;  /* 从24px增大到28px */
  /* color: white; */
}

.config-section {
  background: rgba(37, 37, 37, 0.8);
  border-radius: 8px;
  padding: 1rem;
  margin-bottom: 2rem;
}

.config-section h2 {
  font-family: 'Noto Sans SC', sans-serif;
  font-weight: 500;
  font-size: 18px;
  /* color: white; */
  margin-bottom: 1rem;
}

.config-controls {
  display: flex;
  gap: 1rem;
}

.config-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.config-item label {
  font-family: 'Noto Sans SC', sans-serif;
  color: white;
}

.config-item select {
  background: #333;
  color: white;
  border: 1px solid #444;
  padding: 0.5rem;
  border-radius: 4px;
}

.input-section {
  display: flex;
  gap: 1rem;
  margin-bottom: 2rem;
}

.deep-think-btn {
  background: #8b5cf6;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 0 1.5rem;
  font-family: 'Noto Sans SC', sans-serif;
  cursor: pointer;
}

.input-box {
  flex: 1;
  display: flex;
  background: #333;
  border-radius: 6px;
  padding: 0.5rem 1rem;
}

.input-box input {
  flex: 1;
  background: transparent;
  border: none;
  color: white;
  outline: none;
}

.input-icons {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.send-btn {
  background: #8b5cf6;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0.25rem;
  cursor: pointer;
}

.preview-section {
  background: rgba(37, 37, 37, 0.8);
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  border: 1px solid rgba(139,92,246,0.2);
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid rgba(255,255,255,0.1);
}

.preview-header h2 {
  font-family: 'Noto Sans SC', sans-serif;
  font-weight: 500;
  font-size: 20px;
  color: white;
  margin: 0;
}

.preview-controls {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.preview-controls select {
  background: #333;
  color: white;
  border: 1px solid #444;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.preview-controls select:focus {
  border-color: #8b5cf6;
  outline: none;
}

.regenerate-btn {
  background: linear-gradient(135deg, #8b5cf6 0%, #6366f1 100%);
  color: white;
  border: none;
  border-radius: 6px;
  padding: 0.5rem 1.5rem;
  font-family: 'Noto Sans SC', sans-serif;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.regenerate-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.3);
}

.question-card {
  background: #252525;
  border-radius: 8px;
  padding: 1rem;
  margin-bottom: 1rem;
  display: block !important;  /* 确保显示 */
  opacity: 1 !important;     /* 确保不透明 */
}

.question-content {
  font-family: 'Noto Sans SC', sans-serif;
  font-size: 16px;
  color: white;
  margin-bottom: 0.5rem;
}

.question-meta {
  display: flex;
  justify-content: space-between;
  font-family: 'Noto Sans SC', sans-serif;
  font-size: 14px;
  color: #aaa;
  margin-bottom: 0.5rem;
}

.question-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

.question-actions i {
  cursor: pointer;
}

.question-actions i:nth-child(1) {
  color: #10b981;
}

.question-actions i:nth-child(2) {
  color: #f59e0b;
}

.question-actions i:nth-child(3) {
  color: #ef4444;
}

.edit-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-overlay {
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.7);
  backdrop-filter: blur(5px);
}

.dialog-content {
  position: relative;
  background: #252525;
  border-radius: 12px;
  padding: 2rem;
  width: 600px;
  max-width: 90%;
  box-shadow: 0 10px 25px rgba(0,0,0,0.3);
  border: 1px solid rgba(139,92,246,0.3);
}

.dialog-content h3 {
  margin-top: 0;
  color: white;
  font-family: 'Noto Sans SC', sans-serif;
  font-size: 1.5rem;
  margin-bottom: 1.5rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #ddd;
  font-family: 'Noto Sans SC', sans-serif;
}

.form-group textarea,
.form-group input,
.form-group select {
  width: 100%;
  padding: 0.8rem;
  background: #333;
  border: 1px solid #444;
  border-radius: 8px;
  color: white;
}

.form-group textarea {
  min-height: 150px;
  resize: vertical;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1.5rem;
}

.confirm-btn {
  background: #8b5cf6;
  color: white;
  border: none;
  padding: 0.6rem 1.2rem;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.cancel-btn {
  background: #444;
  color: white;
  border: none;
  padding: 0.6rem 1.2rem;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.confirm-btn:hover {
  background: #7c3aed;
  transform: translateY(-1px);
}

.cancel-btn:hover {
  background: #555;
  transform: translateY(-1px);
}

/* 新增确认对话框样式 */
.confirm-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.preview-text {
  padding: 0.8rem;
  background: #333;
  border-radius: 8px;
  color: white;
  font-family: 'Noto Sans SC', sans-serif;
}

/* 添加过渡动画样式 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.math-formula {
  font-family: 'Times New Roman', serif;
  font-style: italic;
}

pre {
  background-color: #333;
  padding: 1rem;
  border-radius: 8px;
  overflow-x: auto;
}

code {
  font-family: 'Courier New', monospace;
}

/* 添加旋转动画 */
.spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
